using System;
using UnityEngine;

namespace MultiplayerServerConnectionHandlers
{
	public class AcceptConnectionsHandler : MessageHandler
	{
		public delegate void OnConnectionEstablished();

		public int maxConnections = 1;

		public event OnConnectionEstablished onNewConnection;

		public override bool CanAcceptMessage(UDPMessageBase message)
		{
			return message.type == UDPMessageBase.MessageType.RequestConnection;
		}

		public override void OnMessageReceived(UDPMessageBase message)
		{
			Debug.Log("AcceptConnectionsHandler - OnMessageReceived");
			ConnectionHandler connectionHandler = null;
			int num = 0;
			foreach (MessageHandler handler in server.handlers)
			{
				ConnectionHandler connectionHandler2 = handler as ConnectionHandler;
				if (connectionHandler2 != null)
				{
					num++;
					if (connectionHandler2.receiver.Address.Equals(message.senderAddress) && connectionHandler2.receiverId == message.senderId)
					{
						connectionHandler = connectionHandler2;
					}
				}
			}
			if (num < maxConnections && connectionHandler == null)
			{
				EstablishNewConnection(message);
			}
			else if (connectionHandler == null && num >= maxConnections)
			{
				RejectNewConnection(message);
			}
		}

		private void EstablishNewConnection(UDPMessageBase message)
		{
			Debug.Log("EstablishNewConnection");
			ConnectionHandler connectionHandler = new ConnectionHandler(message.senderAddress, message.senderPort);
			connectionHandler.isReceiverIdKnown = true;
			connectionHandler.lastReceievedMessageTime = DateTime.Now;
			connectionHandler.receiverId = message.senderId;
			server.AddHandler(connectionHandler);
			if (this.onNewConnection != null)
			{
				this.onNewConnection();
			}
		}

		private void RejectNewConnection(UDPMessageBase message)
		{
			RejectConnectionMessage rejectConnectionMessage = new RejectConnectionMessage(message.senderId);
			server.SendMessage(message.senderAddress, message.senderPort, rejectConnectionMessage.SerializeToBytes());
		}
	}
}
